<template>
  <div class="common_wrap">
    <div class="common_title">人员管理</div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="已同步人员" name="1"></el-tab-pane>
      <el-tab-pane label="通讯录" name="2"></el-tab-pane>
    </el-tabs>
    <el-form ref="queryForm" :model="queryParams" label-width="60px" inline class="search-nav">
      <el-form-item prop="name" label="姓名">
        <el-input placeholder="请输入姓名" v-model="queryParams.name"></el-input>
      </el-form-item>
      <el-form-item v-if="activeName == 1" prop="phone" label="手机号">
        <el-input placeholder="请输入手机号" v-model="queryParams.phone"></el-input>
      </el-form-item>
      <el-form-item v-if="activeName == '1'" prop="areaList" label="地区">
        <!-- <el-select v-model="queryParams.areaId" placeholder="请选择地区" filterable clearable>
          <el-option
            v-for="(item, index) in areaList"
            :key="item.areaId + index"
            :label="item.areaName"
            :value="item.areaId"
          />
        </el-select> -->
            <el-cascader
            @change="changeSearch"
            clearable
            v-model="queryParams.areaList"
            filter
            :options="areaList"
            :props="{ value:'areaId',label:'areaName',children:'childList',checkStrictly: true  }"
           
          ></el-cascader>
      </el-form-item>
      <el-form-item prop="govEmpPosJob" label="职务">
        <el-input placeholder="请输入职务" v-model="queryParams.govEmpPosJob"></el-input>
      </el-form-item>
      <el-form-item prop="roleId" label="角色" v-if="activeName == 1">
        <el-select placeholder="请选择角色" v-model="queryParams.roleId" filterable clearable>
          <el-option v-for="(item) in roleList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item prop="dingAccountId" label="钉ID">
        <el-input placeholder="请输入钉ID" v-model="queryParams.dingAccountId"></el-input>
      </el-form-item>
      <el-form-item prop="value" label>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="display:flex;width:100% ">
      <!-- v-if="activeName == '2'"" -->
      <div v-show="activeName == '2'" class="xyOverFolw">
        <el-tree
          :props="props"
          :load="loadNode"
          node-key="organizationCode"
          @node-click="getCheckedNodes"
          lazy
          @check-change="handleCheckChange"
        ></el-tree>
      </div>
      <div :style="{width:activeName == '1' ? '100%' :'calc(100% - 250px)'}">
        <el-table v-if="activeName == 1" :data="synchronizationList" style="width: 100%">
          <el-table-column prop="dingAccountId" label="钉ID" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" align="center"></el-table-column>
          <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
          <el-table-column prop="areaName" label="地区" align="center">
            <template slot-scope="{row}">
              <div>{{row.areaName}} {{row.streetName}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="organizationName" label="部门" align="center"></el-table-column>
          <el-table-column prop="govEmpPosJob" label="职务" align="center"></el-table-column>
          <el-table-column prop="level" label="角色" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.level == -1">镇（街）负责人</span>
              <span v-if="scope.row.level == 0">区负责人</span>
              <span v-if="scope.row.level == 1">区主职</span>
              <span v-if="scope.row.level == 2">市管领导</span>
              <span v-if="scope.row.level == 3">市直领导</span>
            </template>
          </el-table-column>
          <el-table-column prop="workTask" label="分管工作" align="center"></el-table-column>
          <el-table-column prop="address" label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="edit(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-table
          v-if="activeName == 2"
          :data="tableData.slice((pageNum-1)*pageSize,pageNum*pageSize)"
          style="width: 100%;height:calc(100vh - 350px);overflow-y: auto;"
        >
          <el-table-column prop="accountInfo.accountId" label="钉ID" align="center"></el-table-column>
          <el-table-column prop="employeeName" label="姓名" align="center"></el-table-column>
          <!-- <el-table-column prop="address" label="手机号" align="center"></el-table-column> -->
          <el-table-column prop="divisionName" label="地区" align="center"></el-table-column>
          <el-table-column prop="organizationName" label="部门" align="center"></el-table-column>
          <el-table-column prop="govEmployeePositions[0].govEmpPosJob" label="职务" align="center"></el-table-column>
          <el-table-column prop="address" label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="tongbu(scope.row)">同步</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-pagination
          :page-size="pageSize"
          :current-page="pageNum"
          layout="prev, pager, next"
          @current-change="currentChange"
          :total="total"
        ></el-pagination>-->
        <el-pagination
          style="text-align:center"
          @size-change="handleSizeChange"
          @current-change="currentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑 -->
    <el-dialog title="编辑" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="地区">
          <!-- <el-select placeholder="请选择地区" v-model="form.areaId" filterable clearable>
            <el-option
              v-for="(item, index) in areaList"
              :key="item.areaId + index"
              :label="item.areaName"
              :value="item.areaId"
            />
          </el-select>-->
        
          <el-cascader
            v-model="form.areaList"
            filter
            :options="areaList"
            :props="{ value:'areaId',label:'areaName',children:'childList',checkStrictly: true  }"
            @change="handleChangeEdit"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="部门">
          <el-input placeholder="请输入部门" v-model="form.organizationName"></el-input>
        </el-form-item>
        <el-form-item label="职务">
          <el-input placeholder="请输入职务" v-model="form.govEmpPosJob"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select placeholder="请选择角色" v-model="form.level" filterable clearable>
            <el-option
              v-for="(item) in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分管工作">
          <el-input :disabled="form.level != 0" type="textarea" autosize v-model="form.workTask"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      idCity:'',
      roleList: [
        {
          name: "镇（街）负责人",
          id: -1
        },
        {
          name: "区负责人",
          id: 0
        },
        {
          name: "区主职",
          id: 1
        },
        {
          name: "市管领导",
          id: 2
        },
        {
          name: "市直领导",
          id: 3
        }
      ],
      dialogVisible: false,
      queryParams: {
        name: "",
        areaList:"",
        phone: "",
        areaId: "",
        govEmpPosJob: "",
        roleId: "",
        streetId:"",
        dingAccountId: ""
      },

      synchronizationList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      synchronizationTotal: 1,
      deptList: [],
      areaList: [],
      tableData: [],
      tableData1: [],
      activeName: "1",
      props: {
        label: "organizationName",
        children: "zones"
      },
      count: 1,
      form: {
        name: "",
        phone: "",
        areaList: "",
        areaId:'',
        areaName: "",
        streetId: null,
        streetName: null,
        organizationName: "",
        govEmpPosJob: ""
      }
    };
  },
  mounted() {
   
    this.getAreaList();
    // this.getdeptList();
    this.getData();
  },
  methods: {
    changeSearch () {
      if(this.queryParams.areaList.length == 3 || this.queryParams.areaList.length == 2) {
        this.queryParams.areaId = this.queryParams.areaList[1]
      this.queryParams.streetId = this.queryParams.areaList[2]
      } else if (this.queryParams.areaList.length == 1) {
        this.queryParams.areaId = this.queryParams.areaList[0]
        this.queryParams.streetId = ''
      } else {
        this.queryParams.areaId = ''
        this.queryParams.streetId = ''
      }
      
    },
     handleChangeEdit () {
       console.log(this.areaList,this.form.areaList)
       if(this.form.areaList.length == 1) {
          this.form.areaId = this.areaList[0].areaId
          this.form.areaName = this.areaList[0].areaName
          this.form.streetName = ''
          this.form.streetId  = ''
          return
       }
       
       let list = this.areaList[0].childList.filter(item => item.areaId == this.form.areaList[1])[0]
       console.log(list)
       this.form.areaId = list.areaId
       this.form.areaName = list.areaName
     
      if(this.form.areaList.length > 2) {
        let streetList = list.childList
        console.log(streetList)
        let list1 = streetList.filter(item => item.areaId == this.form.areaList[2])[0]
        this.form.streetName = list1.areaName
        this.form.streetId = list1.areaId
      } else {
        this.form.streetName = ''
        this.form.streetId = ''
      }
      console.log(this.form.areaId,this.form.areaName,this.form.streetId,this.form.streetName)
      
    },
    edit(row) {
      this.dialogVisible = true;
      this.form = Object.assign({}, row);
      // this.form.areaList = [row.areaId,row.streetId ? row.streetId : '']
      let a = []
      if(this.idCity != row.areaId) {
          a.push(this.idCity)
      }
      
      a.push(row.areaId)
      row.streetId ? a.push(row.streetId) : ''
      console.log(a)
      this.$set(this.form,'areaList',a)
    },
    handleClick(e) {
      console.log(this.activeName);
      this.$refs.queryForm.resetFields();
      this.queryParams.areaId = ''
      this.queryParams.streetId = ''
      this.search();
    },
    addSubmit() {
      if (this.form.phone) {
        if (!/^1[3456789]\d{9}$/.test(this.form.phone)) {
          this.$message.warning("手机号码有误，请重填");
          return false;
        }
      }
      this.$api.editUserInfo(this.form).then(res => {
        this.$message.success("编辑成功");
        this.dialogVisible = false;
        this.getData();
      });
    },
    getData() {
      this.$api
        .getPersonInfo(
          Object.assign(this.queryParams, {
            pageNo: this.pageNum,
            pageSize: this.pageSize
          })
        )
        .then(res => {
          this.synchronizationList = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    tongbu(row) {
      this.$api
        .getByAccountId({ accountId: row.accountInfo.accountId })
        .then(res => {
          if (res.data.data) {
            this.$confirm("当前用户已同步，确认同步后会更新为最新数据", "提示", {
              confirmButtonText: "确定",
              showCancelButton: false
            }).then(res => {
              this.tijiao(row);
            });
          } else {
            this.tijiao(row);
          }
        });
    },
    tijiao(row) {
      let params = {
        dingAccountId: row.accountInfo.accountId,
        employeeCode: row.employeeCode,
        name: row.employeeName,
        phone: "",
        areaId: row.divisionCode,
        areaName: row.divisionName,
        organizationName: row.organizationName,
        govEmpPosJob: row.govEmployeePositions[0].govEmpPosJob,
        level: ""
      };
      this.$api.synUserInfo(params).then(res => {
        this.$message.success('同步成功')
      });
    },
    search() {
      if (this.activeName == 1) {
        this.pageNum = 1;
        this.getData();
      } else {
        this.pageNum = 1;
        this.getMailList();
      }
    },
    getMailList() {
      let data = this.tableData1;
      let a;
      if (this.queryParams.name) {
        this.tableData = data.filter(item =>
          item.employeeName.includes(this.queryParams.name)
        );
      } else {
        this.tableData = data;
      }
      if (this.queryParams.govEmpPosJob) {
        a = [];
        this.tableData.forEach(item => {
          let d = item.govEmployeePositions.some(
            // i => i.govEmpPosJob == this.queryParams.govEmpPosJob
            i => i.govEmpPosJob.includes(this.queryParams.govEmpPosJob)
          );
          if (d) {
            a.push(item);
          }
        });
        console.log(a);
        this.tableData = a;
      } else {
        this.tableData = this.tableData;
      }

      if (this.queryParams.dingAccountId) {
        this.tableData = this.tableData.filter(item => {
          console.log(item.accountInfo.accountId);
          return item.accountInfo.accountId == this.queryParams.dingAccountId;
        });
      } else {
        this.tableData = this.tableData;
      }
      //   this.tableData = a
      this.total = this.tableData.length;
    },
    reset() {
      this.$refs.queryForm.resetFields();
      this.queryParams.areaId = ''
      this.queryParams.streetId = ''
      this.search();
    },
    getdeptList() {
      this.$api.deptList().then(res => {
        console.log(res);
        this.deptList = res.data.data.deptList;
      });
    },
    getTreeData(data){

            for(var i=0;i<data.length;i++){

                if(data[i].childList.length<1){

                // children若为空数组，则将children设为undefined

                data[i].childList=undefined;

                }else {

                this.getTreeData(data[i].childList);

                }

            }

            return data;

        },
    getAreaList() {
      this.$api.getTreearea().then(res => {
        this.areaList = this.getTreeData(res.data.data);
        // console.log(this.areaList)
        this.idCity = this.areaList[0].areaId
        // console.log(this.areaList);
      });
      // const params = {
      //   _gp: "area",
      //   _mt: "list"
      // };
      // this.$api.commonApi(params).then(res => {
      //   if (res.data.errno === 200) {
      //     this.areaList = res.data.data.map(item => {
      //       return {
      //         label: item.areaName,
      //         value: item.areaId
      //       };
      //     });
      //   } else {
      //     this.areaList = [];
      //   }
      // });
    },
    getCheckedNodes(data, node, elem) {
      this.$api
        .childDeptOrPeopleList({ organizationCode: node.key })
        .then(res => {
          if (res.data.data.peopleList) {
            this.pageNum = 1;
            this.tableData = res.data.data.peopleList;
            this.tableData1 = res.data.data.peopleList;
            this.$refs.queryForm.resetFields();
            this.total = this.tableData.length;
          } else {
          }
        });
    },
    currentChange(e) {
      this.pageNum = e;
      if (this.activeName == 1) {
        // this.pageInfo.pageNo = 1
        this.getData();
      } else {
        // this.pageNum = 1;
        // this.getMailList();
      }
    },
    handleSizeChange(e) {
      this.pageSize = e;
      if (this.activeName == 1) {
        // this.pageInfo.pageNo = 1
        this.getData();
      } else {
        // this.pageNum = 1;
        // this.getMailList();
      }
    },
    handleCheckChange() {},
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.$api.deptList().then(res => {
          let deptList = res.data.data.deptList;
          return resolve(deptList);
        });
      } else {
        this.$api
          .childDeptOrPeopleList({ organizationCode: node.key })
          .then(res => {
            if (res.data.data.peopleList) {
              this.pageNum = 1;
              this.tableData = res.data.data.peopleList;
              this.tableData1 = res.data.data.peopleList;
              this.$refs.queryForm.resetFields();
              this.total = this.tableData.length;
              return resolve([]);
            } else {
              return resolve(res.data.data.deptList);
            }
          });
      }
    }
  }
};
</script>

<style scoped>
.xyOverFolw {
  width: 250px;

  height: calc(100vh - 300px);
  overflow-y: auto;
  overflow-x: auto;
}
.xyOverFolw >>> .el-tree-node__children {
  overflow: none;
}
.righ1t {
  height: calc(100vh - 300px);
  overflow-y: auto;
}
</style>